<template>
  <div v-loading="loading" class="container">
    <h1>
      图表统计查看
    </h1>
    <el-table :data="farmData" style="width: 100%">
      <el-table-column prop="id" label="农田ID" width="120" />
      <el-table-column prop="farmland_name" label="农田名称" />
      <el-table-column prop="farmland_type" label="农田作物" />
      <el-table-column prop="manager_id" label="负责人" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleView(scope.row)">查看图表统计情况</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="openView" title="图表统计" width="1000px">
      <!-- 这里是图表 -->
      <chart></chart>
      <el-form>
        <el-form-item style="text-align: center;">
          <el-button @click="onClose()">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAllFarmland, getPestDiseaseData, getWeatherData, getSoilData } from '@/api/farmland'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import chart from './chart.vue'

const farmData = ref([])
const loading = ref(false)
const openView = ref(false)
const soilData = ref([])
const pestData = ref([])
const weatherData = ref([])

const getFarmland = async () => {
  try {
    let response = await getAllFarmland()
    response = response.data[0]
    farmData.value = Array.isArray(response) ? response : [response]
  } catch (error) {
    console.error('获取农田数据失败:', error)
  }
}

onMounted(() => {
  getFarmland()
})

const handleView = async () => {
  loading.value = true
  await setTimeout(() => {
    loading.value = false
    openView.value = true
  },30000)
  // getChart()
}

const getChart = async () => {
  try {
    // 获取土壤/气象/病虫数据
    await fetchSoilData(row.id)
    await fetchPestData(row.id)
    await fetchWeatherData()

    // 接入 AI 获取图表
    const res = await axios({
      url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
      headers: {
        'Authorization': 'Bearer sk-975cabb58b8740cdb71bf3f653a8d3e7', // 确保 API 密钥正确
        'Content-Type': 'application/json'
      },
      method: 'post',
      data: {
        model: "default-model", // 切换到其他模型
        messages: [
          {
            role: "user",
            content: "你好，请你根据给出农田的土壤墒情数据，病虫害数据，气象数据，统计一下这个农田后续的生长状况与作物收获状况等等图表，使用element-plus框架来生成chart图表来显示在界面上，要求直接返回带有数据的html代码,直接返回html代码就好了，不要返回除代码外的其他内容，也不用返回 最终答案: ```html ```等等，直接就是html代码,谢谢" +
              JSON.stringify(soilData.value) +
              JSON.stringify(pestData.value) +
              JSON.stringify(weatherData.value)
          }
        ]
      }
    })
    // 获取答案
    console.log("最终答案:", res.data.choices[0].message.content)
    chartHtml.value = res.data.choices[0].message.content
  } catch (error) {
    console.error('调用大模型失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取土壤数据
const fetchSoilData = async (farmland_id) => {
  try {
    const response = await getSoilData(farmland_id)
    const responseData = response.data[0]
    soilData.value = Array.isArray(responseData) ? responseData : [responseData]
  } catch (error) {
    console.error('获取土壤数据失败:', error)
    ElMessage.error('获取土壤数据失败')
    soilData.value = []
  }
}

// 病虫数据
const fetchPestData = async (farmland_id) => {
  try {
    let response = await getPestDiseaseData(farmland_id)
    pestData.value = response.data[0]
  } catch (err) {
    console.error('Error fetching data:', err)
  }
}

// 气象数据
const fetchWeatherData = async () => {
  try {
    const response = await getWeatherData()
    console.log(response.data[0])
    weatherData.value = response.data[0]
  } catch (error) {
    console.error('获取气象数据失败', error)
  }
}

const onClose = () => {
  openView.value = false
}
</script>

<style scoped>
.container {
  padding: 20px;
}
h1 {
  margin-bottom: 20px;
}
.el-card {
  margin-bottom: 20px;
}
</style>